package 
{
	import Interfaces.MIAppStarter;
	
	import Miscellaneous.GameInitParser;
	
	import RendererUltility.ScreenAlignment;
	
	import XFComponent.XFProgressBar;
	
	import XMFramework.Core.SCore;
	
	import com.demonsters.debugger.MonsterDebugger;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.UncaughtErrorEvent;
	import flash.system.ApplicationDomain;
	import flash.text.TextField;
	
	import flashx.textLayout.formats.BackgroundColor;
	
	import org.aswing.graphics.Pen;
	
	[SWF( frameRate="24", width="836", height="640")]
	public class cgkproj_preloader extends Sprite implements MIAppStarter
	{
		private var snsEngine : SCore					=	null;
		
		private var gameContainer : Sprite 				= 	new Sprite();
		
		// Application info
		private var appWidth : int						=	ShareConstant.APP_SCREEN_WIDTH;
		private var appHeight : int						=	ShareConstant.APP_SCREEN_HEIGHT;
		
		// Loading screen UI
		[Embed(source="E:/Soft/xampp/htdocs/CGKGame/compile/media/swf/LoadingScreen.swf", symbol="LoadingScreen")]
		private static const loadingBackgoundClass : Class;
		
		[Embed(source="E:/Soft/xampp/htdocs/CGKGame/compile/media/swf/LoadingScreen.swf", symbol="ProgressBar")]
		private static const progressBarClass : Class;
		
		private var loadingContainer : Sprite			=	new Sprite();
		private var loadingBackgoundAsset : Sprite		=	null;
		/*private var progressBarAsset : Sprite			=	null;
		private var prbLoading : XFProgressBar			=	null;
		private var lblLoadingPercent : TextField		=	null;
		private var lblLoadingDetail : TextField		=	null;*/
		
		private var socialParams : Object				=	
			{ 
				uid : "1", 
				sid : "1",
				sig: "1",
				username: "username1",
				mediaPath : "E:/Soft/xampp/htdocs/CGKGame/compile/media/", 
				requireAssets:"",
				isNewPlayer:"0",
				hostPath : "./", 
				configPath: "E:/Soft/xampp/htdocs/CGKGame/compile/media/json/",
				helpBookPath: "E:/Soft/xampp/htdocs/CGKGame/compile/media/help/",
				topEggEventPath: "http://www.google.com",
				externalLog: "",
				gateway : "http://projp2.server.local/gateway.php", 
				service_name : "GameService", 
				service_method : "loadGame",
				patchFile : ""	// Empty string to turn off patch file
			};
		
		
		private var sysConfigsData : Array	=	[	
			"media.json",
			"system.json",
			"penguins.json"/*,
			"items.csv",
			"penguins.csv"*/
		];
		
		public function cgkproj_preloader()
		{
			this.addEventListener( Event.ADDED_TO_STAGE, onAddToStage );
			loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler ); 
		}
		
		protected function onBackgroundLoadingAsset():void
		{
			if( loadingBackgoundAsset == null )
			{
				loadingBackgoundAsset = new loadingBackgoundClass;
			}
			loadingContainer.addChild( loadingBackgoundAsset );
			
			// Disabled mouse input from user
			this.mouseEnabled = false;
			this.mouseChildren = false;
			
			// Init loading status
		}
		
		protected function onAddToStage(event:Event):void
		{
			// Attach Monster Debugger
			MonsterDebugger.initialize( this );
			MonsterDebugger.inspect(this);
			
			// Add container for all Game component
			addChild( gameContainer );
			addChild( loadingContainer );
			
			onBackgroundLoadingAsset();
			
			var requireAssetArr:Array = [];
			if( socialParams.requireAssets != null && socialParams.requireAssets.length != 0 )
				requireAssetArr	=	socialParams.requireAssets.split( ";" );
			
			
			snsEngine	=	new SCore();
			
			try
			{
				snsEngine.start( 
					this,
					socialParams.hostPath, 
					socialParams.mediaPath, 
					socialParams.configPath,
					sysConfigsData,
					socialParams.patchFile,
					requireAssetArr,
					onFrameworkInitResult );
			}
			catch(e:*){}
		}
		
		private function onFrameworkInitResult( errCode : int, errMsg : String, ...params ):void
		{
			// Handle Success code
			if( errCode >= 0 )
			{
				switch( errCode )
				{
					case SCore.START_UP:
						
						// Application info
						snsEngine.globalHolder.setVariable( ShareMacros.VAR_APP_WIDTH, appWidth );
						snsEngine.globalHolder.setVariable( ShareMacros.VAR_APP_HEIGHT, appHeight );
						snsEngine.globalHolder.setVariable( ShareMacros.VAR_APP_ROOT, this );
						
						snsEngine.globalHolder.setVariable( ShareMacros.VAR_GAME_CONTAINER, gameContainer );
						
						break;
					
					case SCore.SUCCESS:
						
						// Start internal client timer collapse to server time
						snsEngine.timer.tickingServerTime	=	socialParams["bootrapTime"];
						
						// Start CCU monitor system
						CCUMonitor.start( socialParams.ccuServerAdd, socialParams.ccuServerPort, socialParams.ccuPingDelay );
						
						appWidth	=	stage.stageWidth;
						appHeight	=	stage.stageHeight;
						
						drawDefaultBackroundColor( 0x95cb3f );
						
						// Register global server data response function 
						snsEngine.networkSystem.addGlobalResponseListener( onServerDataResponse );	
						
						// Broadcast application init success to all module
						snsEngine.broadcasting( null, ShareMacros.MBROADCASTING_AppInitComplete );
						
						GameInitParser.doStartingGame( snsEngine );
						
						break;
					
					case SCore.RESOURCE_LOAD:
						break;
					
					case SCore.RESOURCE_LOAD_COMPLETE:	
						onLoadedResourceComplete();
						break;			
					
					case SCore.INIT_MODULE:	
						break;
				}
			}
		}
		
		private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
		{
			
		}
	
		private function onServerDataResponse( error:int, mid:int, cid:int, msg:String, params : * ):void 
		{
			
		}
		
		private function onLoadedResourceComplete():void
		{
			unlockScreen();
			
			var currentDomain:ApplicationDomain	=	ApplicationDomain.currentDomain;
			try
			{
				var penguinsCageClass:Class			=	currentDomain.getDefinition( "PenguinsCageScene" ) as Class;
				if( penguinsCageClass == null )
				{
					trace( "Not found penguins cage" );
					return;
				}
				
				var penguinsCage:DisplayObject		=	new penguinsCageClass;
				gameContainer.addChild( penguinsCage );
			}
			catch(e:*){}
		}
		
		public function setFullscreenMode( fullscreen : Boolean ) : void
		{
		}
		public function isFullscreenMode() : Boolean
		{
			return false;
		}
		
		public function getWidth() : int
		{
			return appWidth;
		}
		
		public function getHeight() : int
		{
			return appHeight;
		}
		
		public function getHostContainer() : DisplayObjectContainer
		{
			return this;
		}
		
		public function getUIContainer() : Array
		{
			return null;
		}
		
		public function getSessionParamsPtr() : Object
		{
			return null;
		}
		public function packSessionData() : Array
		{
			return null;
		}
		public function equivalentSession( obj1:Array, obj2:Array ) : Boolean
		{
			return true;
		}
		public function setSessionParamsPtr( value : Object ) : void
		{
		}
		
		public function unlockScreen() : void
		{
			if( loadingContainer != null )
			{
				try { removeChild( loadingContainer ); }
				catch( ex:* ){}
				
				
				// Enabled mouse input from user
				this.mouseEnabled = true;
				this.mouseChildren = true;
				
				loadingBackgoundAsset = null;
			}
		}
		
		public function getContainerOrderMode() : String
		{
			return "";
		}
		
		public function getAMFGatewayInfo() : Object
		{
			var network : Object		=	new Object;
			
			network["gateway"]			=	socialParams.gateway;
			network["service_name"]		=	"GameService";
			network["service_method"]	=	socialParams.service_name
			network["social"]			=	socialParams.service_method;
			
			return network;
		}
		
		public function getSocialParams() : Object
		{
			return this.socialParams;
		}
		
		public function getIsoContainer() : DisplayObjectContainer
		{
			return null;
		}
		
		public function drawDefaultBackroundColor( color:uint=0x000000 ):void
		{
			var g:Graphics = this.graphics;
			g.beginFill( color );
			g.drawRect( 0, 0, this.stage.stageWidth, this.stage.stageHeight );
			g.endFill();
		}
		
		public function getCacheGameInitData():*
		{
			
		}
		
		public function fetchCacheGameInitSession():*
		{
			
		}
		
		public function isNewPlayer():Boolean
		{
			return true;
		}
		
		public function updateContainerOrderMode( mode : String ) : void
		{	
		}
	}
}